package server;

import java.util.HashMap;
import java.util.Map;

public class Mapper {
    private Map<String, Host> hostMapping = new HashMap<>();

    public Map<String, Host> getHostMapping() {
        return hostMapping;
    }

    public void setHostMapping(Map<String, Host> hostMapping) {
        this.hostMapping = hostMapping;
    }

    // host:localhost uri:/demo1/lagou
    public HttpServlet findServlet(String host, String uri) {
        if (uri == null){
            return null;
        }

        if (!hostMapping.containsKey(host)) {
            System.out.println("unmatched host:" + host);
            return null;
        }

        Host mappedHost = hostMapping.get(host);
        // /demo1
        String contextPath = "/" + uri.split("/")[1];
        if (!mappedHost.getContextMapping().containsKey(contextPath)) {
            System.out.println("unmatched contextPath:" + contextPath);
            return null;
        }

        Context mappedContext = mappedHost.getContextMapping().get(contextPath);
        // /lagou
        String urlPattern = uri.substring(uri.indexOf(contextPath) + contextPath.length());

        if (!mappedContext.getServletMapping().containsKey(urlPattern)) {
            return null;
        }

        return mappedContext.getServletMapping().get(urlPattern);
    }
}